﻿using System.Data.Entity;
using System.Linq;
using YogaStudio.Data;
using YogaStudio.Data.Domain;

namespace YogaStudio.Service.BLL
{
    public class UserManagementService : IUserManagementService
    {
        public void AddUser(User user)
        {
            using (var context = new YogaStudioEntities())
            {
                context.Users.Add(user);
                context.SaveChanges();
            }
        }

        public void UpdateUser(User user)
        {
            using (var context = new YogaStudioEntities())
            {
                context.Entry(user).State = EntityState.Modified;
                context.SaveChanges();
            }
        }

        public User GetUser(string userName)
        {
            using (var context = new YogaStudioEntities())
            {
                var user = context.Users.SingleOrDefault(u => u.UserName == userName);
                return user;
            }
        }

        public User ConfirmUserRegistration(User user)
        {
            using (var context = new YogaStudioEntities())
            {
                context.Entry(user).State = EntityState.Modified;
                context.SaveChanges();
                return user;
            }
        }

        public User GetUser(string userName, string password)
        {
            using (var context = new YogaStudioEntities())
            {
                var user = context.Users.SingleOrDefault(u => u.UserName == userName && u.Password == password && u.isConfirmed);
                return user;
            }
            
        }

        

        public void AddUserRole(UserRole userRole)
        {
            using (var context = new YogaStudioEntities())
            {
                var roleEntry = context.UserRoles.SingleOrDefault(r => r.UserId == userRole.UserId);
                if (roleEntry != null)
                {
                    context.UserRoles.Remove(roleEntry);
                    context.SaveChanges();
                }
                context.UserRoles.Add(userRole);
                context.SaveChanges();
            }
            
        }

    }
}
